package com.jianyitech.asr.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpHelper {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 发送POST请求
     * @param url
     * @param body
     * @return
     * @throws IOException
     */
    public static String sendPost(String url,String body) throws IOException {

        X509TrustManager manager = getX509TrustManager();
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(5,TimeUnit.SECONDS)
                .sslSocketFactory(getSocketFactory(manager),manager)
                .hostnameVerifier(getHostnameVerifier())
                .build();
        RequestBody requestBody = RequestBody.create(JSON, body);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Response response = client.newCall(request).execute();
        if(response.isSuccessful()){
            return response.body().string();
        }else{
            throw new IOException("Unexpected code "+ response);
        }
    }



    /**
     * 发送POST请求
     * @param url
     * @param body
     * @return
     * @throws IOException
     */
    public static String sendPost(String url, Map<String,String> headers, String body) throws IOException {

        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(5,TimeUnit.SECONDS)
                .build();
        RequestBody requestBody = RequestBody.create(JSON,StringUtil.trim(body));
        Request request = new Request.Builder().headers(Headers.of(headers)).url(url).post(requestBody).build();
        Response response = client.newCall(request).execute();
        if(response.isSuccessful()){
            return response.body().string();
        }else if(response.code()==401 || response.code()==403){
            Map<String,Object> map = new HashMap<>();
            map.put("success",false);
            map.put("message","Unauthorized");
            return JSONObject.toJSONString(map);
        }else{
            throw new IOException("Unexpected code "+ response);
        }
    }



    private static SSLSocketFactory getSocketFactory(TrustManager manager) {
        SSLSocketFactory socketFactory = null;
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{manager}, new SecureRandom());
            socketFactory = sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return socketFactory;
    }


    private static X509TrustManager getX509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

    private static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }







}
